package com.ithm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ithm.reggie.common.R;
import com.ithm.reggie.entity.User;
import com.ithm.reggie.service.UserService;
import com.ithm.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * UserControal
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 发送手机短信验证码
     *
     * @param user
     * @return
     */

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession httpSession) {
        log.info("user:{}", user.toString());
        //获取手机号
        String phone = user.getPhone();
        String subject = "瑞吉餐购登录验证码";
        if (phone != null) {

            //生成随机验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            String context = "欢迎使用瑞吉餐购，登录验证码为: " + code + ",五分钟内有效，请妥善保管!";
            //调用阿里云短信服务API发送短信
            userService.sendMsg(phone, subject, context);
            log.info("code:{}", code);
            //将验证码保存到Session
            httpSession.setAttribute(phone, code);
            return R.success("短信发送成功");
        }

        return R.error("短信发送失败");
    }

    /**
     * 登录功能
     * @param map
     * @param httpSession
     * @return
     */
    @PostMapping("/login")
    public R<String> login(@RequestBody Map  map, HttpSession httpSession) {
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从Session中获取验证码
        String codeInSession = (String) httpSession.getAttribute(phone);
        //比较验证码
        if (codeInSession != null && codeInSession.equals(code)) {
            //如果验证码正确，根据手机号查询用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            //判断用户是否存在
            if (user == null) {
                //如果用户不存在，则创建新用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //将用户id保存到Session
            httpSession.setAttribute("user", user.getId());
            return R.success("登录成功");
        }

        return R.error("登录失败");
    }
}
